<template>
  <div class="map" id="map"></div>
</template>

<script>
import "ol/ol.css";
import Draw from "ol/interaction/Draw";
import Map from "ol/Map";
import View from "ol/View";
import TileArcGISRest from "ol/source/TileArcGISRest";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource, Cluster } from "ol/source";
import {
  Circle as CircleStyle,
  Fill,
  Stroke,
  Style,
  Text,
  Icon
} from "ol/style";
import Point from "ol/geom/Point";
import Feature from "ol/Feature";

import mapData from "./data.js";
import pointImg from "@/images/device.png";
import CONSTANT from "@/config/constant.js";

const SEARCH_RADIUS = 200;

export default {
  name: "CircleSearch",

  data() {
    return {
      map: null,
      sourceCluster: null, //点位图层
      drawSource: null,
      drawVector: null,
      shape: null,
      selectedFeatures: [] //画图监所到的图层
    };
  },

  methods: {
    init() {
      //初始化地图
      this.map = new Map({
        layers: [
          new TileLayer({
            source: new TileArcGISRest({
              url: CONSTANT.GIS_URL
            })
          })
        ],
        target: "map",
        view: new View({
          center: [113.0567, 23.67537],
          maxZoom: 18,
          minZoom: 8,
          zoom: 13,
          projection: "EPSG:4326"
        })
      });

      this.showPoints();

      this.addDrawLayer();
    },

    // 展示聚合点位
    showPoints() {
      // 聚合图层数据源
      this.sourceCluster = new Cluster({
        distance: 100,
        source: new VectorSource({
          features: []
        })
      });

      const vectorLayer = new VectorLayer({
        source: this.sourceCluster,
        style: feature => {
          return this.setClusterStyle(feature);
        }
      });

      let features = [];
      mapData.forEach(item => {
        if (item.gps_x != "" && item.gps_y != "") {
          let newObj = Object.assign({}, item);
          newObj.geometry = new Point([Number(item.gps_x), Number(item.gps_y)]);
          features.push(new Feature(newObj));
        }
      });
      this.sourceCluster.getSource().addFeatures(features);
      this.map.addLayer(vectorLayer);

      /* 
        mapData是数组，每一项结构：
        {
            "domain_id": 10000029,
            "domain_name": "深圳市第一看守所",
            "domain_type_name": "看守所",
            "gps_x": "113.0131",
            "gps_y": "23.71433",
            "count": 0,
            "channel_id": "",
            "group_idx": 1
        } */
    },

    // 增加绘画图层
    addDrawLayer() {
      this.drawSource = new VectorSource({ wrapX: false });
      this.drawVector = new VectorLayer({
        source: this.drawSource
      });
      this.map.addLayer(this.drawVector);

      this.drawCircle();
    },

    //绘制圆
    drawCircle() {
      this.shape = new Draw({
        source: this.drawSource,
        type: "Circle",
        stopClick: true
        // geometryFunction: this.geometryFunction(value)
      });

      this.map.addInteraction(this.shape);

      //绘画开始
      this.shape.on("drawstart", data => {
        this.selectedFeatures.splice(0, this.selectedFeatures.length);
      });

      //监听绘画结束
      this.shape.on("drawend", evt => {
        var polygon = evt.feature.getGeometry();
        var center = polygon.getCenter(),
          radius = polygon.getRadius();
        var extent = polygon.getExtent();
        var features = this.sourceCluster
          .getSource()
          .getFeaturesInExtent(extent); //先缩小feature的范围
        for (var i = 0; i < features.length; i++) {
          var newCoords = features[i].getGeometry().getCoordinates();
          if (this.pointInsideCircle(newCoords, center, radius)) {
            this.selectedFeatures.push(features[i]);
          }
        }

        alert("选择的设备数：" + this.selectedFeatures.length);
        console.log(JSON.stringify(this.selectedFeatures, null, 4));
      });
    },

    /**
     *  判断一个点是否在圆的内部
     *  @param point  测试点坐标
     *  @param circle 圆心坐标
     *  @param r 圆半径
     *  返回true为真，false为假
     *  */
    pointInsideCircle(point, circle, r) {
      if (r === 0) return false;
      var dx = circle[0] - point[0];
      var dy = circle[1] - point[1];
      return dx * dx + dy * dy <= r * r;
    },

    //设置聚合图层的样式
    setClusterStyle(feature) {
      var features = feature.get("features");
      var size = features.length;
      var style;
      if (size == 1) {
        style = [
          new Style({
            image: new Icon({
              src: pointImg
            })
          })
        ];
      } else {
        style = new Style({
          image: new CircleStyle({
            radius: 18,
            stroke: new Stroke({
              color: "#fff"
            }),
            fill: new Fill({
              color: "#3399CC"
            })
          }),
          text: new Text({
            font: "15px sans-serif",
            text: size.toString(),
            fill: new Fill({
              color: "#fff"
            })
          })
        });
      }
      return style;
    }
  },

  mounted() {
    this.init();
  }
};
</script>

<style lang="less" scoped>
.map {
  height: 100%;
}
</style>